package com.hankol.newretail

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.util.Log
import android.view.View
import androidx.lifecycle.Observer
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import cn.iwgang.countdownview.CountdownView
import com.alibaba.android.arouter.facade.annotation.Route
import com.baselibrary.Constants
import com.baselibrary.MessageBus
import com.baselibrary.extension.checkNotNull
import com.baselibrary.extension.setMallPriceTTF
import com.baselibrary.extension.toast
import com.baselibrary.manager.DialogManager
import com.baselibrary.manager.LoadingManager
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.*
import com.baselibrary.activity.BaseActivity
import com.hankol.material.PayManager
import com.hankol.newretail.bean.PayResultBean
import com.hankol.newretail.databinding.ActivitySelectPayWayBinding
import com.hankol.newretail.utils.RetailPopUtils
import com.hankol.newretail.viewmodel.SelectPayStyleViewModel
import com.hanxiang.hankol.wxapi.WXManager
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/*支付 选择方式*/
@Route(path = ActivityRouter.NEW_RETAIL.SELECT_PAY_WAY)
class SelectPayWayActivity : BaseActivity(), View.OnClickListener {

    private lateinit var viewModel: SelectPayStyleViewModel
    private lateinit var binding: ActivitySelectPayWayBinding
    private var dialogCountdownView: CountdownView? = null

    //是否 超时
    private var isOutTime = false
    private var poids = ""
    private var overtime = 0L
    private var shouldPayPrice = 0L
    private var payOid = 0L

    //支付方式
    private var payType = 0
    private var isUsePay = false
    private var isOnceFail = false
    var ccbPayType = 0

    companion object {
        //key 购买数量（从商品详情进入）
        const val KEY_POIDS = "poids"
        const val KEY_OVERTIME = "overtime"
        const val KEY_SHOULD_PAY_PRICE = "shouldPayPrice"
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_select_pay_way
    }

    override fun onResume() {
        super.onResume()
        //仅处理微信
        if (isUsePay && payOid != 0L && viewModel.isSelectWeChat.get()!!) {
            //  支付 订单结果查询
            viewModel.requestPayIsSucc("${payOid}")
        }
    }

    override fun init() {
        ccbPayType = SpUtils.getInt(this, Constants.KEY_CONFIG_CCB_PAY_TYPE, 0)
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        binding = getDataBinding()
        viewModel = getActivityViewModelProvider(this).get(SelectPayStyleViewModel::class.java)
        viewModel.requestData()
        myRegister()
        initData()
    }

    private lateinit var receiver: MyBroadcastReceiver

    private fun myRegister() {
        receiver = MyBroadcastReceiver()
        LocalBroadcastManager.getInstance(applicationContext).registerReceiver(receiver, IntentFilter(Config.wechat_pay_result))
    }

    private fun initData() {
        if (ARouterUtils.parseParams(intent.extras!!, KEY_POIDS)[0].checkNotNull()) {
            poids = ARouterUtils.parseParams(intent.extras!!, KEY_POIDS)[0]
        }
        if (ARouterUtils.parseParams(intent.extras!!, KEY_OVERTIME)[0].checkNotNull()) {
            overtime = ARouterUtils.parseParams(intent.extras!!, KEY_OVERTIME)[0].toLong()
        }
        if (ARouterUtils.parseParams(intent.extras!!, KEY_SHOULD_PAY_PRICE)[0].checkNotNull()) {
            shouldPayPrice = ARouterUtils.parseParams(intent.extras!!, KEY_SHOULD_PAY_PRICE)[0].toLong()
        }
        binding.tvShouldPayPrice.text = "${AmountUtil.changeF2YKeepTwo("${shouldPayPrice}")}"
        binding.tvShouldPayPrice.setMallPriceTTF(this)
        binding.tvUnit.setMallPriceTTF(this)
        showBottomStatus()
        if (ccbPayType == 1) {//0-微信支付宝，1-建行支付
            binding.rlAir.visibility = View.GONE
        } else {
            binding.rlAir.visibility = View.VISIBLE
        }
        binding.rlWechat.setOnClickListener(this)
        binding.rlAir.setOnClickListener(this)
        binding.llBottom.setOnClickListener(this)
        binding.backImageView.setOnClickListener {
            //弹窗提示：是否放弃本次付款
            showCancelPayDialog()
        }
        val tempTime = overtime.minus(TimeUtil.getCurrentTimeMillis())
        binding.countdownView.customTimeShow(tempTime >= 1000 * 60 * 60 * 24, tempTime >= 1000 * 60 * 60, true, true, false)
        binding.countdownView.start(tempTime)
        binding.countdownView.setOnCountdownIntervalListener(1000, object : CountdownView.OnCountdownIntervalListener {
            override fun onInterval(cv: CountdownView?, remainTime: Long) {
                Log.d("王小鹏", "onInterval: $remainTime")
                dialogCountdownView?.updateShow(remainTime)
            }

        })
        binding.countdownView.setOnCountdownEndListener {
            var poIdsStr = ""
            if (poids.startsWith("[")) {
                poIdsStr = poids
            } else {
                poIdsStr = "[${poids}]"
            }
            val poidList = CommonUtil.jsonToList(poIdsStr, String::class.java)
            viewModel.requestOverTimeNoPayCancel(poidList[0])

        }
        //微信支付1
        viewModel.creatPayWX.observe(this, Observer { it ->
            if (it != null) {
                payOid = it

                if (ccbPayType == 1) {
                    //跳转小程序支付
                    WXManager.jumpToWxExe(this, "gh_5f0490804c92", "activityPackage/pages/pay/appPayInWx?old=${it}")
                } else {
                    viewModel.requestPay4WX(it)
                }
            } else {
                LoadingManager.hideProgress(this)
            }
        })
        //支付宝支付1
        viewModel.creatPayZFB.observe(this, Observer { it ->
            if (it != null) {
                payOid = it
                viewModel.requestPay4ZFB(it)
            } else {
                LoadingManager.hideProgress(this)
            }
        })
        //微信支付2
        viewModel.pay4WX.observe(this, Observer { it ->
            it?.let {
                val appId = it.appid
                val partnerId = it.partnerid
                val prepayId = it.prepayid
                val nonceStr = it.noncestr
                val timeStamp = it.timestamp
                val sign = it.sign
                PayManager.WeChatPay(this, appId, partnerId, prepayId, nonceStr, timeStamp, sign)
                isUsePay = true
            }
        })
        //支付宝支付2
        viewModel.pay4ZFB.observe(this, Observer { it ->

            it?.let {
                PayManager.aliPay(this, it, object : PayManager.PayListener {
                    override fun onSuccess() {
                        LoadingManager.hideProgress(this@SelectPayWayActivity)
                        viewModel.requestPayIsSucc("${payOid}")
                    }

                    override fun onFail() {
                        binding.llBottom.isClickable = true
                        LoadingManager.hideProgress(this@SelectPayWayActivity)
                        "支付未成功，请重新付款".toast()
                    }

                    override fun onCancel() {
                        binding.llBottom.isClickable = true
                        "支付未成功，请重新付款".toast()
                        LoadingManager.hideProgress(this@SelectPayWayActivity)
                    }
                })
                isUsePay = true
            }
        })
        //检查是否支付成功
        viewModel.payIsSuccLD.observe(this, Observer { it ->
            if (it.checkNotNull()) {
                payComplete(it)
            } else {
                if (!isOnceFail) {
                    isOnceFail = true
                    binding.llBottom.postDelayed(Runnable {
                        viewModel.requestPayIsSucc("${payOid}")
                    }, 2000)
                } else {
                    LoadingManager.hideProgress(this)
                    "支付未成功，请重新付款".toast()
                }
            }
            binding.llBottom.isClickable = true
        })
        viewModel.overTimeCancelLD.observe(this, Observer {
            "订单已关闭，请重新下单！".toast()
            isOutTime = true
            //进入订单详情
            val hashMap = java.util.HashMap<String, Any>()
            var poIdsStr = ""
            if (poids.startsWith("[")) {
                poIdsStr = poids
            } else {
                poIdsStr = "[${poids}]"
            }
            val poidList = CommonUtil.jsonToList(poIdsStr, String::class.java)
            if (poidList.size == 1) {
                hashMap[Constants.KEY_ORDER_ID] = poidList[0]
                ARouterUtils.jump(ActivityRouter.NEW_RETAIL.ORDER_DETAIL, hashMap)
                finish()
            } else {
                finish()
            }
        })
    }

    private fun showBottomStatus() {
        binding.tvBottomPayPrice.text = "${OptionUtils.payType(payType)} ¥${AmountUtil.changeF2YKeepTwo("${shouldPayPrice}")}"
        binding.tvBottomPayPrice.setMallPriceTTF(this)
    }

    var isClickWait = false
    private fun showCancelPayDialog() {
        if (poids.checkNotNull() && !isClickWait) {
            dialogCountdownView = RetailPopUtils.showPayBackDialog(this, overtime, object : RetailPopUtils.ICallback4Ok {
                override fun onClickOk() {
                    EventBusUtils.sendNotify(MessageBus.msgId_refresh_goods_detail)
                    //进入订单详情
                    val hashMap = java.util.HashMap<String, Any>()
                    var poIdsStr = ""
                    if (poids.startsWith("[")) {
                        poIdsStr = poids
                    } else {
                        poIdsStr = "[${poids}]"
                    }
                    val poidList = CommonUtil.jsonToList(poIdsStr, String::class.java)
                    if (poidList.size == 1) {
                        hashMap[Constants.KEY_ORDER_ID] = poidList[0]
                        ARouterUtils.jump(ActivityRouter.NEW_RETAIL.ORDER_DETAIL, hashMap)
                    } else {
                        // 跳转 待付款列表页
                        hashMap[Constants.KEY_ORDER_TYPE] = 0
                        ARouterUtils.jump(ActivityRouter.NEW_RETAIL.MY_ORDER, hashMap)
                    }
                    finish()
                }

                override fun onClickWait() {
                    isClickWait = true
                }
            })
            dialogCountdownView?.customTimeShow(overtime.minus(TimeUtil.getCurrentTimeMillis()) >= 1000 * 60 * 60 * 24, overtime.minus(TimeUtil.getCurrentTimeMillis()) >= 1000 * 60 * 60, true, true, false)
        } else {
            finish()
        }
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.rl_wechat -> {
                binding.cbWechat.isChecked = true
                binding.cbAir.isChecked = false
                viewModel.isSelectWeChat.set(true)
                payType = 0
                showBottomStatus()
            }
            R.id.rl_air -> {
                binding.cbWechat.isChecked = false
                binding.cbAir.isChecked = true
                viewModel.isSelectWeChat.set(false)
                payType = 1
                showBottomStatus()
            }
            R.id.ll_bottom -> {
                if (isOutTime) {
                    //超时
                    showToast("订单已关闭，请重新下单！")
                    //进入订单详情
                    val hashMap = java.util.HashMap<String, Any>()
                    var poIdsStr = ""
                    if (poids.startsWith("[")) {
                        poIdsStr = poids
                    } else {
                        poIdsStr = "[${poids}]"
                    }
                    val poidList = CommonUtil.jsonToList(poIdsStr, String::class.java)
                    if (poidList.size == 1) {
                        hashMap[Constants.KEY_ORDER_ID] = poidList[0]
                        ARouterUtils.jump(ActivityRouter.NEW_RETAIL.ORDER_DETAIL, hashMap)
                        finish()
                    } else {
                        finish()
                    }
                    return
                }
                //支付提交
                if (HKUtils.isFastClick()) {
                    payCommit()
                }
            }
        }
    }

    //支付提交
    private fun payCommit() {
        if (viewModel.isSelectWeChat.get()!!) {
            //判断是否安装app
            if (!CommonUtil.isInstallWx(this)) {
                DialogManager.showConfirmDialog_hideLeft(this, "提示", "您没有安装微信，请先安装后才能付款", null)
                return
            }
            binding.llBottom.isClickable = false
            LoadingManager.showProgress(this, "请稍后...")
            //微信支付
            isUsePay = true
            viewModel.createPayOrder4wx(poids)
        } else {
            //判断是否安装支付宝app
            if (!CommonUtil.isInstallAliPay(this)) {
                DialogManager.showConfirmDialog_hideLeft(this, "提示", "您没有安装支付宝，请先安装后才能付款", null)
                return
            }
            binding.llBottom.isClickable = false
            //支付宝支付
            LoadingManager.showProgress(this, "请稍后...")
            viewModel.createPayOrder4zfb(poids)
        }
    }

    internal inner class MyBroadcastReceiver : BroadcastReceiver() {

        override fun onReceive(context: Context, intent: Intent) {
            LoadingManager.hideProgress(this@SelectPayWayActivity)
            val action = intent.action
            if (Config.wechat_pay_result == action) {
                val result = intent.getBooleanExtra("result", false)
                val errCode = intent.getIntExtra("errCode", -1)
                if (result) {
                    viewModel.requestPayIsSucc("${payOid}")
                } else {
                    binding.llBottom.isClickable = true
                    if (errCode == -2) {//取消

                    } else {

                    }
                }
            }
        }
    }

    //支付完----支付成功
    fun payComplete(it: PayResultBean) {
        LoadingManager.hideProgress(this)
        EventBusUtils.sendNotify(MessageBus.msgId_pay_success)
        val hashMap = java.util.HashMap<String, Any>()
        hashMap[PaySuccessActivity.KEY_POIDS] = poids
        hashMap[PaySuccessActivity.KEY_PAY_PRICE_SUM] = "${it.payPriceSum}"
        hashMap[PaySuccessActivity.KEY_SCORE_DEDUCTPRICE_SUM] = "${it.scoreDeductPriceSum}"
        hashMap[PaySuccessActivity.KEY_SHOULD_REWARD_SCORE] = "${it.shouldRewardScore}"
        ARouterUtils.jump(ActivityRouter.NEW_RETAIL.PAY_SUCCESS, hashMap)
        finish()
    }

    override fun onDestroy() {
        EventBusUtils.sendNotify(MessageBus.msgId_finish_pay_mall)
        LocalBroadcastManager.getInstance(applicationContext).unregisterReceiver(receiver)
//        AppManager.getAppManager().finishActivity(ShopCartListActivity::class.java)
        super.onDestroy()
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
    }

    override fun onBackPressed() {
        showCancelPayDialog()
//        super.onBackPressed()
    }

    //EventBus 接受方法
    @Subscribe(threadMode = ThreadMode.MAIN) fun onEvent(messageBus: MessageBus) {
        if (messageBus.codeType == MessageBus.msgId_wx_miniprogram_pay_success) {//小程序返回APP

        }
    }
}